﻿// Licensed under GNU GPL V2.
// http://sps2010listmanager.codeplex.com/
// (c) 2010 by Daniel Bedarf

using System;
using System.Collections.Generic;
using System.Windows;
using Extensions;

namespace CodePlex.DBedarf.Sharepoint.ListManager
{
    /// <summary>
    /// Interaktionslogik für ListEventhandler.xaml
    /// </summary>
    public partial class FieldPropertyPage : AvalonDock.DocumentContent
    {

        //TODO R2: connect all chkBoxes to _bSomeThingChanged

        List<Microsoft.SharePoint.SPField> _fields;
        bool _bSomeThingChanged;

        RoutedEventHandler refreshFields;
        logJournalMessageDelegate log;

        /// <summary>
        /// Initializes a new instance of the <see cref="FieldPropertyPage"/> class.
        /// </summary>
        /// <param name="fields">The fields.</param>
        /// <param name="refreshFieldsMethod">The refresh fields method.</param>
        /// <param name="logMethod">The log method.</param>
        public FieldPropertyPage(RoutedEventHandler refreshFieldsMethod, logJournalMessageDelegate logMethod)
        {
            InitializeComponent();

            refreshFields = refreshFieldsMethod;
            log = logMethod;
            _bSomeThingChanged = false;
        }


        /// <summary>
        /// Sets the fields to edit.
        /// </summary>
        /// <value>The fields.</value>
        public List<Microsoft.SharePoint.SPField> Fields
        {
            set
            {
                if (_bSomeThingChanged) if (WindowExtender.AskYesNo("Changes detected", "There are unsaved changes to the columns.\n\nDo you want to drop that changes?") == false) return;

                _fields = value;
                if (_fields != null)
                {
                    stpEdit.IsEnabled = (_fields.Count > 0);

                }
                else stpEdit.IsEnabled = false;

                Action_GetFieldValues();
            }
        }

        /// <summary>
        /// read all field props and set it to the ui
        /// </summary>
        private void Action_GetFieldValues()
        {
            if (_fields.Count > 1)
            {
                xCaml.Visibility = Visibility.Hidden;
                xName.Visibility = Visibility.Hidden;
            }
            else
            {
                xCaml.Visibility = Visibility.Visible;
                xName.Visibility = Visibility.Visible;
            }

            txtColumns.Text = "";
            //Buttons entsprechend der Fields vorbelegen
            bool bFirst = true;
            foreach (Microsoft.SharePoint.SPField field in _fields)
            {
                if (!bFirst) txtColumns.Text += ", ";
                txtColumns.Text += field.Title;

                if (bFirst)
                {
                    chkShowNewForm.IsChecked = field.ShowInNewForm;
                    chkShowEditForm.IsChecked = field.ShowInEditForm;
                    chkShowViewForm.IsChecked = field.ShowInViewForms;
                    chkShowDisplayForm.IsChecked = field.ShowInDisplayForm;
                    chkShowSettings.IsChecked = field.ShowInListSettings;

                    chkIsRequiered.IsChecked = field.Required;
                    txtSchema.Text = field.SchemaXml;
                    txtStaticName.Text = field.StaticName;

                    bFirst = false;
                }//end if bFirst
                {
                    //vergleichen der bisher gesetzten Werte, dann evtl. grau fären

                    //show
                    if (chkShowNewForm.IsChecked != field.ShowInNewForm)
                        chkShowNewForm.IsChecked = null;

                    if (chkShowEditForm.IsChecked != field.ShowInEditForm)
                        chkShowEditForm.IsChecked = null;

                    if (chkShowViewForm.IsChecked != field.ShowInViewForms)
                        chkShowViewForm.IsChecked = null;

                    if (chkShowDisplayForm.IsChecked != field.ShowInDisplayForm)
                        chkShowDisplayForm.IsChecked = null;

                    if (chkShowSettings.IsChecked != field.ShowInListSettings)
                        chkShowSettings.IsChecked = null;

                    //Access
                    if (chkIsRequiered.IsChecked != field.Required)
                        chkIsRequiered.IsChecked = null;

                    if (chkCanDeleted.IsChecked != !field.AllowDeletion)
                        chkCanDeleted.IsChecked = null;

                    if (chkReadOnly.IsChecked != field.ReadOnlyField)
                        chkReadOnly.IsChecked = null;

                    if (chkHidden.IsChecked != field.Hidden)
                        chkHidden.IsChecked = null;

                    if (chkNoCrawlBySearchEngine.IsChecked != field.NoCrawl)
                        chkNoCrawlBySearchEngine.IsChecked = null;

                }
            }
            _bSomeThingChanged = false;
        }

        /// <summary>
        /// Handles the SaveSettings event of the Useraction control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_SaveSettings(object sender, RoutedEventArgs e)
        {
            foreach (Microsoft.SharePoint.SPField field in _fields)
            {
                try
                {

                    string msg = "";
                    bool needUpdate = false;
                    if (chkShowNewForm.IsChecked != field.ShowInNewForm)
                    {
                        needUpdate = true;
                        field.ShowInNewForm = chkShowNewForm.IsChecked;
                        msg += "ShowInNewForm: " + chkShowNewForm.IsChecked.ToString() + ", ";
                    }

                    if (chkShowEditForm.IsChecked != field.ShowInEditForm)
                    {
                        needUpdate = true;
                        field.ShowInEditForm = chkShowEditForm.IsChecked;
                        msg += "ShowInEditForm: " + chkShowEditForm.IsChecked.ToString() + ", ";
                    }

                    if (chkShowViewForm.IsChecked != field.ShowInViewForms)
                    {
                        needUpdate = true;
                        field.ShowInViewForms = chkShowViewForm.IsChecked;
                        msg += "ShowInViewForms: " + chkShowViewForm.IsChecked.ToString() + ", ";
                    }

                    if (chkShowDisplayForm.IsChecked != field.ShowInDisplayForm)
                    {
                        needUpdate = true;
                        field.ShowInDisplayForm = chkShowDisplayForm.IsChecked;
                        msg += "ShowInDisplayForm: " + chkShowDisplayForm.IsChecked.ToString() + ", ";
                    }

                    if (chkShowSettings.IsChecked != field.ShowInListSettings)
                    {
                        needUpdate = true;
                        field.ShowInListSettings = chkShowSettings.IsChecked;
                        msg += "ShowInListSettings: " + chkShowSettings.IsChecked.ToString() + ", ";
                    }

                    //Access
                    if (chkIsRequiered.IsChecked != field.Required && chkIsRequiered.IsChecked != null)
                    {
                        needUpdate = true;
                        field.Required = (bool)chkIsRequiered.IsChecked;
                        msg += "Required: " + chkIsRequiered.IsChecked.ToString() + ", ";
                    }

                    if (chkCanDeleted.IsChecked != field.AllowDeletion && chkCanDeleted.IsChecked != null)
                    {
                        needUpdate = true;
                        field.AllowDeletion = chkCanDeleted.IsChecked;
                        msg += "AllowDeletion: " + chkCanDeleted.IsChecked.ToString() + ", ";
                    }

                    if (chkReadOnly.IsChecked != field.ReadOnlyField && chkReadOnly.IsChecked != null)
                    {
                        needUpdate = true;
                        field.ReadOnlyField = (bool)chkReadOnly.IsChecked;
                        msg += "ReadOnly: " + chkReadOnly.IsChecked.ToString() + ", ";
                    }

                    if (chkHidden.IsChecked != field.Hidden && chkHidden.IsChecked != null)
                    {
                        needUpdate = true;
                        field.Hidden = (bool)chkHidden.IsChecked;
                        msg += "Hidden: " + chkHidden.IsChecked.ToString() + ", ";
                    }

                    if (chkNoCrawlBySearchEngine.IsChecked != field.NoCrawl && chkNoCrawlBySearchEngine.IsChecked != null)
                    {
                        needUpdate = true;
                        field.NoCrawl = (bool)chkNoCrawlBySearchEngine.IsChecked;
                        msg += "NoCrawl: " + chkNoCrawlBySearchEngine.IsChecked.ToString() + ", ";
                    }
                    if (_fields.Count == 1)
                    {
                        if (field.StaticName.Equals(txtStaticName.Text) == false)
                        {
                            needUpdate = true;
                            msg += string.Format("change StaticName from \"{0}\" to \"{1}\"", field.StaticName, txtStaticName.Text);
                            field.StaticName = txtStaticName.Text;
                        }
                    }

                    if (needUpdate)
                    {
                        field.Update();
                        if (log != null) log(false, "change column \"{0}\" set: {1}", field.Title, msg);
                    }
                }
                catch (Exception ex)
                {
                    if (log != null)
                    {
                        log(true, "Error while set propertys on column \"{0}\". Message: {1}", field.Title, ex.Message);
                    }
                    else
                    {
                        //alternate
                        HandleError(ex);
                    }
                }

            }//end for each field
            _bSomeThingChanged = false;
            //TODO R3 - Selection geht verloren bei RefreshFields, evtl. verhindern...
            //if (refreshFields != null) refreshFields(sender, e);
        }

        /// <summary>
        /// Handles the Refresh event of the Useraction control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_Refresh(object sender, RoutedEventArgs e)
        {
            try
            {
                Action_GetFieldValues();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        /// <summary>
        /// Handles the error.
        /// </summary>
        /// <param name="ex">The ex.</param>
        private void HandleError(Exception ex)
        {
            WindowExtender.ShowError(ex);
        }
    }
}